const express = require('express')
const router = express.Router()
const db = require('../../connection/Connection')
const jwt = require('jsonwebtoken')
const SECRET = 'asdfta219*&%^jWJSHFJ'


router.post('/addProject', async (req, res) => {
    console.log(req.body)
    //token
    const result = jwt.verify(req.body.token, SECRET)
    let sql = 'select departmentId from user_role where username = ?'
    db.base(sql, result.username, response_temp => {
        if (response_temp != null) {
            sql = 'INSERT INTO project (project_name,difficulty_level,project_leader,department_id,project_start,project_end,project_content,participants) VALUES(?,?,?,?,?,?,?,?)'
            let data = [
                req.body.projectName,
                req.body.difficultLevel,
                req.body.projectLeader,
                response_temp[0].departmentId,
                req.body.projectStart,
                req.body.projectEnd,
                req.body.projectContent,
                req.body.participants]
            db.base(sql, data, response => {
                console.log(response)
                if (response.affectedRows !=null ) {
                    sql = 'SELECT project_id FROM project WHERE project_name = ? and project_leader = ?'
                    data = [req.body.projectName, req.body.projectLeader]
                    db.base(sql, data, response => {
                        let sqltemp1 = 'UPDATE employees SET current_task = CASE work_number'
                        var participantsTemp = new Array();
                        participantsTemp = req.body.participants.split(",");
                        let sqltemp2 = ''
                        for (i = 0; i < participantsTemp.length; i++) {
                            sqltemp2 = sqltemp2 + ' WHEN '
                            sqltemp2 = sqltemp2 + '?'
                            sqltemp2 = sqltemp2 + ' THEN '
                            sqltemp2 = sqltemp2 + response[0].project_id
                        }
                        sqltemp2 = sqltemp2 + ' END WHERE work_number IN ('
                        sqltemp2 = sqltemp2 + req.body.participants
                        sqltemp2 = sqltemp2 + ')'
                        sql = sqltemp1.concat(sqltemp2)
                        console.log(sql)
                        db.base(sql,participantsTemp,response=>{
                            console.log(response)
                        })
                    })
                    res.json({
                        result:"success"
                    })
                } else {
                    res.json({
                        result: false
                    })
                }
            })
        } else {
            res.json({
                result:"error",
                reason:"无权限"
            })
        }
    })
})

module.exports = router
